/********************************************************************
 
 Copyright (C), 2012年 dhc. All rights reserved.
 
 Filename: 	    MailStafferList.m
 
 Author:        muzongcun
 
 Version:       1.0
 
 Description:   MailStafferList
 
 History:
 
 muzongcun    2012/3/10     1.0     Create
 
 *********************************************************************/

#import "MailCCFriendList.h"
#import "MailPersonInfoCell.h"
#import "XmlRpc.h"
#import "Type.h"
#import "Session.h"
#import "TaskManager.h"
//static int baseFriendCount = 10;

@implementation MailCCFriendList

@synthesize m_listTV;
@synthesize m_navBar;
@synthesize m_contentArray;
@synthesize m_bIsSearching;
@synthesize m_searchBar;
@synthesize m_searchScopeType;  
@synthesize _refreshHeaderView;
@synthesize _refreshFooterView;
@synthesize m_mailCCFriendListDelegate;
@synthesize m_searchDisplayController;

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{

	if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) 
	{
        //从服务器取得朋友列表
		m_contentArray = [[NSMutableArray alloc]initWithCapacity:0];
	}
	return self;
}

- (void)viewDidLoad 
{
    //默认是不进行搜索
    m_bIsSearching = NO;
    
    //默认使按照联系人进行搜索
    m_searchScopeType = @"02";
    
    //设置导航栏背景颜色
    UIImage* imageBar = [UIImage imageNamed:@"TabBarGradient@2x"];
    [self.navigationController setNavigationBarHidden:NO];
    
    NSString* devVersion = [[UIDevice currentDevice] systemVersion];
    if ([devVersion compare:@"4.3.3"] == 0)
    {
        [self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)];
        [self.navigationController.navigationBar setTintColor:NAVIGATION_BAR_COLOR];
    }else
    {
       [self.navigationController.navigationBar setBackgroundImage:imageBar forBarMetrics:UIBarMetricsDefault];
    }
    
    
	m_listTV = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 44.0, 320.0, 480.0-20-44) style:UITableViewStylePlain];
	m_listTV.delegate = self;
	m_listTV.dataSource = self;
	
	m_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)];
	m_searchBar.delegate = self;
	m_searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	m_searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
	m_listTV.tableHeaderView = m_searchBar;
    
    UISearchBar *mySearchBar = m_searchBar;
	[mySearchBar setScopeButtonTitles:[NSArray arrayWithObjects:@"联系人",@"邮箱地址",nil]];
	mySearchBar.delegate = self;
	[mySearchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
	[mySearchBar sizeToFit];
	m_listTV.tableHeaderView = mySearchBar;
    [mySearchBar setTintColor:NAVIGATION_BAR_COLOR];
	m_searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:mySearchBar contentsController:self];
	[m_searchDisplayController setDelegate:self];
	[m_searchDisplayController setSearchResultsDataSource:self];
	[mySearchBar release];
	
    m_moreBtn = [UIButton	buttonWithType:UIButtonTypeCustom];
	[m_moreBtn setTitle:@"" forState:UIControlStateNormal];
	[m_moreBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
	[m_moreBtn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
	[m_moreBtn addTarget:self action:@selector(showMoreContact:) forControlEvents:UIControlEventTouchUpInside];
	m_moreBtn.frame = CGRectMake(0.0, 0.0, 320.0, 44.0);
	m_listTV.tableFooterView = m_moreBtn;
	[self.view addSubview:m_listTV];
    
    /*
	 Hide the search bar
	 */
	[m_listTV setContentOffset:CGPointMake(0, 44.f) animated:NO];
    NSIndexPath *tableSelection = [m_listTV indexPathForSelectedRow];
	[m_listTV deselectRowAtIndexPath:tableSelection animated:NO];
    
    ///////////////////////////////////////////////////
    
    if (_refreshFooterView == nil) 
    {
        
        EGORefreshTableFooterView *view = [[EGORefreshTableFooterView alloc] initWithFrame: CGRectMake(0.0f, self.m_listTV.contentSize.height, self.m_listTV.bounds.size.width,800)];
        //NSLog(@"%@", NSStringFromCGRect( view.frame ));
        view.delegate = self;
        [self.m_listTV addSubview:view];
        self._refreshFooterView = view;
        [view release];
        
    }
    if (_refreshHeaderView == nil) 
    {
        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame: CGRectMake(0,                                                                                                       -800,                                                                                                       self.m_listTV.bounds.size.width,                                                                                                       800)];
        //NSLog(@"%@", NSStringFromCGRect( view.frame ));
        view.delegate = self;
        [self.m_listTV addSubview:view];
        self._refreshHeaderView = view;
        [view release];
    }
	
	//  update the last update date
	[_refreshFooterView refreshLastUpdatedDate];
    [_refreshHeaderView refreshLastUpdatedDate];
    
    //从服务器取得数据
    [self refreshData];
    
    self.m_listTV.backgroundColor=[UIColor whiteColor];
}

- (void)viewDidUnload 
{
    [super viewDidUnload];
    
}

- (void)dealloc 
{
	[m_listTV release];
	[m_searchBar release];
	[m_contentArray release];
    [super dealloc];
}

#pragma mark -
//******************************************************
// Method:     searchBarSearchButtonClicked
// Access:     public 
// Returns:    void
// Parameter:  
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{   
    /*
      遍历当前searchbar中的控件，找到cancel按钮，并修改为中文
      */
    m_searchBar.showsCancelButton = YES;
    for(id ctl in [m_searchBar subviews])
    {
        if([ctl isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)ctl;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
	m_searchText = searchBar.text;
    
    [self doSearch];
}
#pragma mark -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    return [m_contentArray count];
}

//******************************************************
// Method:     tableView
// Access:     public 
// Returns:    void
// Parameter:  cellForRowAtIndexPath
// Note:	  
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	static NSString *CellIdentifier = @"MailPersonInfoCell";
    
	MailPersonInfoCell *cell = (MailPersonInfoCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) 
    {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"MailPersonInfoCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        //cell.accessibilityIdentifier = CellIdentifier;
	}
   
    if (indexPath.row >= [m_contentArray count]) 
    {
        return cell;
    }
	NSString *name = [[m_contentArray objectAtIndex:indexPath.row] objectForKey:@"t_1_contact_name"];
    NSString *address = [[m_contentArray objectAtIndex:indexPath.row] objectForKey:@"t_1_mail"];
    
    //通过url取得图片信息
	//UIImage *image =[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: [[m_contentArray objectAtIndex:indexPath.row] objectForKey:@"url"]]]];
    
    UIImage *imagePersonInfo =[UIImage  imageNamed:PIC_MAIL_PERSON_IMAGE];
    UIImageView* personImage = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 30, 30)];
    [personImage setImage:imagePersonInfo];
	cell.personName.text    = name ;
    cell.personAddress.text = address ;
    [cell addSubview:personImage];
    //cell.imageView.frame = CGRectMake(0, 0, 20, 20);
	//[cell.imageView setImage:imagePersonInfo];
    
    // Configure the cell...
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.backgroundView.backgroundColor = [UIColor clearColor];
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
	[m_searchBar resignFirstResponder];
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row >= [m_contentArray count]) 
    {
        return;
    }
    
	[m_mailCCFriendListDelegate addCCMailContact:[m_contentArray objectAtIndex:indexPath.row]];
}

#pragma mark -
//******************************************************
// Method:     readFriendList
// Access:     public 
// Returns:    void
// Parameter:  void
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(NSMutableArray*)readClientList
{
    NSString *num = [[NSString alloc] initWithFormat:@"%i",0];
    NSString *rowsperpage = [NSString stringWithFormat:@"%i",PER_PAGE_ROWS];
    XmlRpc *xml = [[XmlRpc alloc] init];
    NSString *employeeID = @"0002";
    
    NSMutableArray* mailListArray = [xml getMailCustomerList:employeeID positionID:nil startRows:num rowsPerPage:rowsperpage];
    [xml release];
    [num release];
    
	return mailListArray;
}

//******************************************************
// Method:     showMoreContact
// Access:     public 
// Returns:    void
// Parameter:  senders
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(void)showMoreContact:(id)sender
{
	NSLog(@"more");
}

//******************************************************
// Method:     cancelSelected
// Access:     public 
// Returns:    void
// Parameter:  void
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
-(IBAction)cancelSelected:(id)sender
{
	[self dismissModalViewControllerAnimated:YES];
}
-(IBAction)onSearch:(id)sender
{
    m_searchBar.showsCancelButton = YES;
    for(id ctl in [m_searchBar subviews])
    {
        if([ctl isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)ctl;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
        if ([ctl isKindOfClass:[UITextField class]])
        {
            UITextField *txf = (UITextField *)ctl;
            [txf setPlaceholder:@"请输入搜索关键字"];
        }
    }
    [m_searchDisplayController.searchBar setSelectedScopeButtonIndex:0];
    [m_searchDisplayController setActive:YES animated:YES];
}
#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableFooterDidTriggerRefresh:(EGORefreshTableFooterView*)view
{
	
    [self refreshData];
    
	
}
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view
{
	
    [self refreshData];	
}

- (BOOL)egoRefreshTableFooterDataSourceIsLoading:(EGORefreshTableFooterView*)view
{
	
	return _bIsLoading; // should return if data source model is reloading
	
}
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{
	
	return _bIsLoading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableFooterDataSourceLastUpdated:(EGORefreshTableFooterView*)view
{
	
	return [NSDate date]; // should return date data source was last changed
	
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
	
	return [NSDate date]; // should return date data source was last changed
	
}
- (void)reDrawHeaderAndFooter
{
    if (_refreshFooterView != nil) 
    {
        [_refreshFooterView setFrame:CGRectMake(0.0f, self.m_listTV.contentSize.height, self.m_listTV.bounds.size.width,800)];
    }
    if (_refreshHeaderView != nil) 
    {
        
        [_refreshHeaderView setFrame:CGRectMake(0,                                                                                                       -800,                                                                                                       self.m_listTV.bounds.size.width,                                                                                                       800)];
        
    }
    
}
#pragma mark -
#pragma mark UserTaskDelegate Methods
- (void) OnPreExcute 
{
    _bIsLoading = YES;
    [_refreshHeaderView setState:EGOOPullRefreshLoading];
    [_refreshFooterView setState:EGOOPullRefreshLoading];
}

- (void) DoInBackground
{
    int count = [m_contentArray count];
    NSString *num = [NSString stringWithFormat:@"%i",count];
    NSString *rowsperpage = [NSString stringWithFormat:@"%i",PER_PAGE_ROWS];
    XmlRpc *xml = [[XmlRpc alloc] init];
    
    NSString *employeeID = [[Session share] getMemberID];
    
    NSMutableArray* mailListArray = nil;
    
    if (m_bIsSearching) 
    {
        mailListArray = [xml getSearchContactorList:employeeID search_condition:m_searchText search_type:m_searchScopeType startRows:num rowsPerPage:rowsperpage];
    }
    else
    {
        mailListArray = [xml getContactorlist:employeeID startRows:num rowsPerPage:rowsperpage];    
    }


    for (NSMutableDictionary* mailDic in mailListArray)
    {
        //NSString* importFlg = [mailDic objectForKey:@"importantflag"];
        [m_contentArray addObject:mailDic];
    }
     [xml release];
}

- (void) OnPostExcute
{
    _bIsLoading = NO;
    [_refreshFooterView egoRefreshScrollViewDataSourceDidFinishedLoading:self.m_listTV];
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.m_listTV];
    
    [self.m_listTV reloadData];
    [self reDrawHeaderAndFooter];
    //NSLog(@"do post excute");
}
#pragma mark -
#pragma mark Subclass Should Recover these Methods To Get Data
-(void) getMoreData
{
    
    //[[[TaskManager Share] GetTaskByType:HOT_TOPIC_LIST Delegate:self] Excute];
    
}

-(void) refreshData
{
    [[[TaskManager Share] GetTaskByType:mail_GetCustomerList Delegate:self] Excute];
}
#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
    
	[_refreshFooterView egoRefreshScrollViewDidScroll:scrollView];
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
	[_refreshFooterView egoRefreshScrollViewDidEndDragging:scrollView];
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

#pragma mark -
#pragma mark Content Filtering

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
	/*
	 Update the filtered array based on the search text and scope.
	 */
    //	
    //	[self.filteredListContent removeAllObjects];// First clear the filtered array.
    //	
    //	/*
    //	 Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array.
    //	 */
    //	for (Product *product in listContent)
    //	{
    //		if ([scope isEqualToString:@"All"] || [product.type isEqualToString:scope])
    //		{
    //			NSComparisonResult result = [product.name compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
    //            if (result == NSOrderedSame)
    //			{
    //				[self.filteredListContent addObject:product];
    //            }
    //		}
    //	}
}
//******************************************************
// Method:     searchBarTextDidBeginEditing
// Access:     public 
// Returns:    void
// Parameter:  
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    m_searchBar.showsCancelButton = YES;
    for(id cc in [m_searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
    if (self.m_searchBar.showsCancelButton==NO)
    {
        self.m_searchBar.showsCancelButton=YES;
    }
}
#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    NSArray* strscopeButtonTitles = [self.searchDisplayController.searchBar scopeButtonTitles];
    int index = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
    NSString * strScope =  [strscopeButtonTitles objectAtIndex:index];
    [self filterContentForSearchText:searchString scope:strScope];
    return YES;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    NSString* searchText = [self.searchDisplayController.searchBar text];
    NSArray* strscopeButtonTitles = [self.searchDisplayController.searchBar scopeButtonTitles];
    NSString * strScope =  [strscopeButtonTitles objectAtIndex:searchOption];
    
    if ([strScope compare:@"联系人"] == 0) 
    {
        m_searchScopeType = @"02";
    }
    else if([strScope compare:@"邮箱地址"] == 0)
    {
        m_searchScopeType = @"03";
    }
    
    [self filterContentForSearchText:searchText scope:strScope ];
    
    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

//******************************************************
// Method:     searchDisplayControllerDidBeginSearch
// Access:     public 
// Returns:    void
// Parameter:  
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller
{
    
	[self.searchDisplayController.searchResultsTableView setDelegate:self];
    m_searchScopeType = @"02";
}
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller{
	/*
	 Hide the search bar
	 */
	[m_listTV setContentOffset:CGPointMake(0, 44.f) animated:YES];
}
//******************************************************
// Method:     doSearch
// Access:     public 
// Returns:    void
// Parameter:  
// Note:	   
// Author      muzongcun  2012/03/12 create
//*******************************************************
- (void)doSearch
{
    if(m_searchText.length<1)
        return;
    
    self.m_searchBar.showsCancelButton=NO;
    
    m_bIsSearching = YES;
    // [responseParams removeAllObjects];
    
    [m_searchBar resignFirstResponder];
    [self.searchDisplayController setActive:NO];
    [self.m_listTV setContentOffset:CGPointMake(0, 44.f) animated:YES];
    
    [m_contentArray removeAllObjects];
    
    [self.m_listTV reloadData];
    
    [[[TaskManager Share] GetTaskByType:GetProductInfoList Delegate:self] Excute];
}
@end
